<template>
    <div class="iframe">
        <div class="i-title">
            <h3>深度封装</h3>
        </div>
        <div class="i-tip flex">
            <el-input type="number" v-model="num1" /> +
            <el-input type="number" v-model="num2" /> =
            <span class="tip">{{ result }}</span>
        </div>
        <div class="i-tip">
            <el-input type="text" placeholder="请输入用户名" v-model="user.name" />
            <div class="i-tip">用户名：{{user.name}}</div>
            <el-input type="number" v-model="user.age" />
            <div class="i-tip">年龄：{{user.age}}</div>
        </div>
    </div>
</template>

<script>
    import {
        computed,
        reactive,
        ref,
        toRefs,
        onMounted,
        onUnmounted,
        watch
    } from "vue";
    // 加法计算器
    function calculator() {
        // ref函数用来创建一个基本类型的响应式引用，返回值是一个带有value属性的对象,value的初始值为ref的参数值
        let num1 = ref("");
        let num2 = ref("");
        // computed函数用来创建一个计算属性，返回值是计算属性的引用
        let result = computed(() => Number(num1.value) + Number(num2.value));
        return {
            num1,
            num2,
            result,
        };
    }
    // 用户信息
    function getUserInfo() {
        // reactive函数用来创建一个复合数据类型的响应式引用
        let user = reactive({
            name: "张三",
            age: 20,
        });
        // 定义method，需要添加在返回值中，template中才能调用
        function setUserName(e) {
            user.name = "";
        }
        // watch函数用来监听响应式变量变化
        watch(
            () => user.name,
            (val, oldVal) => {
                console.log(`您成功修改用户名为${val},` + user.age);
            }
        );
        // 定义生命周期钩子：在生命周期钩子前添加on
        onMounted(setUserName);
        return {
            user,
            setUserName,
        };
    }
    export default {
        name: "ee",
        setup() {
            let data = calculator();
            let user = getUserInfo();
            return {
                ...data,
                ...user,
            };
        },
    };
</script>
<style scoped>
.flex{
    display: flex;
    align-items: center;
}
</style>

